package com.cosmos.codegen.base.engine;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.cosmos.codegen.base.domain.TableRelationDomain;
import com.cosmos.codegen.base.domain.TemplateDomain;
import com.cosmos.codegen.base.excpetion.NoTablesNameException;
import com.cosmos.codegen.utils.FileUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 
 * @author zhuzhaoyong
 *
 */
public abstract class FreeMarkerEngine {

	private Logger logger = Logger.getLogger(getClass());
	
	// 表集合
	private List<TemplateDomain> tdList = new ArrayList<TemplateDomain>();
	
	@SuppressWarnings("deprecation")
	public void exec(String projectRoot, String dist, String[] tablesName, String prefix) {
		Writer out = null;
		try {
			
			File distFile = new File(dist);
			if(distFile.exists()) {
				// 删除原有目录,重新生成
				FileUtil.deleteFiles(distFile);
			}
			// 创建目录
			distFile.mkdirs();
			Configuration cfg = new Configuration();
			String dir = this.getClass().getResource("ftl").getPath();
			cfg.setDirectoryForTemplateLoading(new File(dir));
			Template template = cfg.getTemplate("base.ftl");
			
			if(null == tablesName || tablesName.length == 0) {
				logger.debug("请设置要生成的实体类对应的表名，字符串数组的形式存在。");
				throw new NoTablesNameException("请填写需要生成的表名");
			}
			
			TableRelationDomain trd = new TableRelationDomain();
			trd.setTablesName(tablesName);
			trd.setPrefix(prefix);
			tdList = generateTableEntity(trd);
			int count = 0;
			StringBuffer teLog = new StringBuffer();
			for(TemplateDomain td : tdList) {
				out = new FileWriter(new File(dist + "/" + StringUtils.capitalize(getClassName(td.getTableName(), prefix)) + ".java"));
				template.process(td, out);
				count ++;
				teLog.append("表" + td.getTableName() + " ==> "
				           + "实体类" + dist + "/" + StringUtils.capitalize(getClassName(td.getTableName(), prefix)) + ".java;");
			}
			// log
			if(count > 0) {
				logger.debug("已经生成 " + count + " 张表的实体类信息: [" + teLog + "]");
				
			} else {
				logger.debug("没有生成表对应的实体类信息");
			}
		} catch(Exception ex) {
			ex.printStackTrace();
		} finally {
			if(null != out) {
				try {
					out.close();
				} catch (IOException e) {
				}
			}
		}
	}
	
	public abstract List<TemplateDomain> generateTableEntity(TableRelationDomain trd);
	
	/**
	 * 去除前缀，获取表名
	 * @param tableName
	 * @param prefix
	 * @return
	 */
	protected String getClassName(String tableName, String prefix) {
		tableName = tableName.toLowerCase();
		prefix    = prefix.toLowerCase();
		return handleSpecialCharacter(tableName.replace(prefix, ""));
	}
	
	protected String handleSpecialCharacter(String columnName) {
		if(StringUtils.isBlank(columnName)) {
			return null;
		}
		// 全部转换成小写来处理
		columnName = columnName.toLowerCase();
		// 遍历特殊字符的位置
		String[] split = columnName.split("_");
		StringBuffer strBuffer = new StringBuffer();
		strBuffer.append(split[0]);
		if(split.length == 1) {
			return strBuffer.toString();
		}
		for(int i = 1; i < split.length; i++) {
			strBuffer.append(StringUtils.capitalize(split[i]));
		}
		return strBuffer.toString();
	}
	
}
